<!--
 * @Description: 重症护理单分页组件
 * @version:
 * @Author: E-CHOOSEUS R&D
 * @LastEditors: Please set LastEditors
-->
<template>
  <div
    class="icrPartialPage"
    :class="{ 'is-border': !printing }"
    :style="{
      height: pageHeight + 'px',
      width: pageA4['297mm'] + 'px'
    }"
  >
    <doc-header
      ref="docHeaderRef"
      :pageConfig="pageConfig"
      :printing="printing"
      :docData="docData"
    />
    <main class="showing-table">
      <!-- <BriefMedicalHistory
        v-if="docTopExtendPage && docTopExtendPage.length > 0"
        ref="medicalHistoryRef"
        :docTopExtendPage="docTopExtendPage"
        :printing="printing"
        :docData="docData"
        :pageConfig="pageConfig"
      /> -->
      <!-- 表格头 -->
      <div v-if="dataList.length > 0" class="showing-thead">
        <icr-render-title
          v-for="(item, idx) in titleColumns"
          :key="idx"
          :column="item"
          :firstRow="dataList[0]"
        />
      </div>
      <!-- 表格行 -->
      <div
        v-for="(vItem, vIdx) in dataList"
        :key="vIdx"
        class="showing-tr"
        :class="{ 'color-bg': vIdx % 2 == 0 }"
        :style="{ height: vItem.height ? vItem.height + 'px' : 'unset' }"
        @dblclick="handleRowClick(vItem, vIdx)"
      >
        <span v-if="vItem.isSummary" class="showing-cell sumCell">
          {{ vItem.date.slice(0, 16) }}
        </span>
        <span v-if="vItem.isSummary" class="showing-cell sumCellText">
          <span>{{ vItem.in }}</span>
          <span>{{ vItem.out }}</span>
        </span>

        <span
          v-for="(hItem, hIdx) in vItem.rData"
          v-else
          :key="hIdx"
          class="showing-cell"
          :style="{
            width:
              (filledCellW[hItem._uuid] && filledCellW[hItem._uuid]._adjusted
                ? filledCellW[hItem._uuid]._fillWidth +
                  filledCellW[hItem._uuid]._stretchW
                : hItem.width +
                  (filledCellW[hItem._uuid]
                    ? filledCellW[hItem._uuid]._stretchW
                    : 0)) + 'px',
            textAlign: hItem.dictValue == 'yx-bqgc' ? 'left' : 'center'
          }"
          @click="handleCellClick(hItem, vIdx, hIdx)"
        >
          <template v-if="hItem.dictValue == 'operater'">
            <img
              v-if="signPhoto(hItem.val, 'nursingDocument', 13)"
              :src="
                'data:image/png;base64,' +
                signPhoto(hItem.val, 'nursingDocument', 13)
              "
              alt=""
              style="
                display: block;
                max-width: 98%;
                max-height: 30px;
                margin: 0 auto;
              "
            />
            <div v-else>{{ hItem.val }}</div>
          </template>
          <span
            v-else
            class="control-text"
            :style="{ width: hItem._noHead ? '100%' : 'unset' }"
          >
            <template v-if="hItem.dictValue == 'date_value'">
              <template v-if="hItem.val">
                <div
                  v-for="(item2, index2) in hItem.val.split(hItem.splicer)"
                  :key="index2"
                >
                  {{ item2.slice(0, 16) }}
                </div>
              </template>
            </template>

            <template v-else-if="hItem.dictValue == 'yx-ysjl'">
              <template v-if="hItem.val">
                <div
                  v-for="(item2, index2) in hItem.val.split(hItem.splicer)"
                  :key="index2"
                >
                  {{ item2 }}
                </div>
              </template>
            </template>

            <template v-else>
              <template v-if="hItem.val">
                <div
                  v-for="(item2, index2) in hItem.val.split(';')"
                  :key="index2"
                  style="width: 100%; text-align: center"
                >
                  {{
                    item2 + (hItem['diy-fieldCode'] == '入量名称' ? '；' : '')
                  }}
                </div>
              </template>
            </template>
          </span>
        </span>
      </div>
    </main>
    <docFooter :pageConfig="pageConfig" />
  </div>
</template>

<script lang="ts">
import { format, startOfDay } from 'date-fns'
import { cloneDeep } from 'lodash-unified'
import { computed, defineComponent, reactive, toRefs, watch } from 'vue'

import { oivolumeExport } from '@/api/nursing/operate'
import { useSign } from '@/hooks'
import { arrSort } from '@/utils/index'
import { getStoreFromInstance } from '@/utils/instance'

// import BriefMedicalHistory from './components/BriefMedicalHistory.vue'
import docFooter from './components/docFooter.vue'
import docHeader from './components/docHeader.vue'
import icrRenderTitle from './components/icrRenderTitle.vue'
import { pageA4 } from './layout-compute'

export default defineComponent({
  name: 'IcrPage',
  components: { docHeader, icrRenderTitle, docFooter },
  props: {
    titleColumns: {
      type: Array,
      default: () => []
    },
    dataList: {
      type: Array,
      default: () => []
    },
    pageConfig: {
      type: Object,
      default: () => ({})
    },
    dataType: {
      type: Number,
      default: 0
    },
    // todo 移除该废弃参数
    fixedCellW: {
      type: Object,
      default: () => ({})
    },
    printing: {
      type: Boolean,
      default: false
    },
    filledCellW: {
      type: Object,
      default: () => ({})
    },
    pageStretchW: {
      type: Number,
      default: 0
    },
    pageHeight: {
      type: Number,
      default: 793
    },
    docData: {
      type: Object,
      default: () => ({})
    },
    docTopExtendPage: {
      type: Array,
      default: () => []
    },
    activeDate: {
      type: Array,
      default: () => []
    }
  },
  emits: ['edit', 'saveCellData'],
  setup(props, { emit }) {
    const state = reactive({
      pageA4,
      recordData: [],
      docHeaderRef: {},
      medicalHistoryRef: {},
      curCellData: {},
      titleColumnsFlat: [],
      dateArr: [],
      dataList: [],
      daySumConfs: {
        daySumTime: {
          in: 'inDaySum',
          out: 'outDaySum'
        },
        nightSumTime: {
          in: 'inNightSum',
          out: 'outNightSum'
        },
        lateNightSumTime: {
          in: 'inLateNightSum',
          out: 'outLateNightSum'
        }
      }
    })

    const store = getStoreFromInstance()
    const { signPhoto } = useSign()

    const patCur = computed(() => store.getters.patCur)
    const roles = computed(() => store.getters.roles)

    function setTitleColumnsFlat(list) {
      list?.forEach(v => {
        const item = cloneDeep(v)
        delete item.childList
        state.titleColumnsFlat.push(item)
        if (v.childList && v.childList.length > 0) {
          setTitleColumnsFlat(v.childList)
        }
      })
    }

    function handleCellClick(hItem, vIdx, hIdx) {
      if (hItem.dictValue === 'operater') {
        const rData = props.dataList[vIdx].rData
        const titleColumnItem = state.titleColumnsFlat.find(
          v => v._uuid === hItem._uuid
        )

        emit('saveCellData', {
          hItem,
          titleColumnItem,
          dateItem: state.dateArr[vIdx],
          vIdx,
          hIdx
        })
      }
    }

    function handleRowClick(item, index) {
      // 行类型为 1 时不显示编辑抽屉
      // if (item.rowType === 1) return
      // emit('edit', index)
    }

    function getDocSaveParams() {
      const form = state.medicalHistoryRef.form
      const evalList = form.nurseEvalList
        .concat(form.doctorEvalList)
        .filter(v => v.dataSource || v.score !== '')
      let docItems = props.docData.docItems
      if (!docItems || docItems.length === 0) {
        docItems = [{}]
      }
      return {
        doc: {
          ...(props.docData.doc || {}),
          hospitalNumber: patCur.value.hospitalNumber,
          patientIdent: patCur.value.patientIdent,
          patientName: patCur.value.patientName,
          docName: '重症护理记录单',
          type: 13,
          createTime: props.docData.doc?.createTime
            ? +new Date(props.docData.doc.createTime)
            : +new Date(),
          jsonText: JSON.stringify({
            zd: state.docHeaderRef.zd,
            gm: form.gm,
            briefMedicalHistory: form.briefMedicalHistory,
            recordTime: form.recordTime,
            recordName: form.recordName
          })
        },
        docItems: docItems.map(v => {
          return {
            ...v,
            createTime:
              v.createTime ||
              format(startOfDay(new Date()), 'yyyy-MM-dd HH:mm:ss'),
            jsonText: JSON.stringify(
              evalList.map(v => {
                return {
                  pgCode: v.pgCode,
                  score: v.score,
                  dataSource: 2
                }
              })
            )
          }
        })
      }
    }

    // 计算出入量总计和大便次数
    async function setSumData(setData) {
      setData.forEach(item => {
        item.date = item.rData[0].val
      })

      const params = {
        patientIdent: patCur.value.patientIdent,
        startTime: +new Date(props.activeDate[0]),
        endTime: +new Date(props.activeDate[1])
      }
      const res = await oivolumeExport(params)
      const tableData: any[] = []
      const outMap = {}
      if (res && res.data) {
        const startRkTime = patCur.value.startRkTime
          ? +new Date(patCur.value.startRkTime)
          : +new Date()
        const endCkTime = patCur.value.endCkTime
          ? +new Date(patCur.value.endCkTime)
          : +new Date()

        const first24Count = true
        for (const key in res.data) {
          if (+new Date(key) < startRkTime || +new Date(key) > endCkTime) {
            continue
          }
          const ObjIn = {},
            ObjSignature = {}
          let strOut = '',
            strIn: any[] = [],
            time = '',
            isSummary = false,
            is24 = false,
            signature: any[] = []
          const item = res.data[key]
          outMap[key] = []
          item.forEach(v => {
            time = format(new Date(key), 'HH:mm')
            if (v.id) {
              if (v.modelCode === 'yx-out') {
                if (strOut !== '') {
                  strOut += '<br />'
                }
                strOut += `${v.medication}：${v.nature || ''} ${v.ioValue}`
                outMap[key].push({
                  medication: v.medication,
                  itemCode: v.itemCode,
                  ioValue: v.ioValue
                })
              } else if (v.modelCode === 'yx-in') {
                const str = `${v.medication}：${v.ioValue}`
                if (v.groupId) {
                  if (!ObjIn[v.groupId]) {
                    ObjIn[v.groupId] = []
                  }
                  ObjIn[v.groupId].push(str)
                  ObjSignature[v.groupId] = v.createName
                } else {
                  if (!ObjIn['noGroupId']) {
                    ObjIn['noGroupId'] = []
                  }
                  ObjIn['noGroupId'].push(str)
                  ObjSignature['noGroupId'] = v.createName
                }
              }
            } else {
              isSummary = true
              if (key == v.daySumTime) {
                strIn.push([
                  `总入量（ml）：${v[state.daySumConfs.daySumTime.in]}`
                ])
                strOut = `总出量（ml）：${v[state.daySumConfs.daySumTime.out]}`
              } else if (key == v.nightSumTime) {
                strIn.push([
                  `总入量（ml）：${v[state.daySumConfs.nightSumTime.in]}`
                ])
                strOut = `总出量（ml）：${
                  v[state.daySumConfs.nightSumTime.out]
                }`
              } else if (key == v.lateNightSumTime) {
                strIn.push([
                  `总入量（ml）：${v[state.daySumConfs.lateNightSumTime.in]}`
                ])
                strOut = `总出量（ml）：${
                  v[state.daySumConfs.lateNightSumTime.out]
                }`
              }
            }
          })

          for (const key_ in ObjIn) {
            if (key_ != 'noGroupId') {
              ObjIn[key_].push('groupId')
            }
          }

          for (const key2 in ObjIn) {
            strIn.push(ObjIn[key2])
            signature.push(ObjSignature[key2])
          }

          tableData.push({
            key,
            date: format(new Date(key), 'yyyy-MM-dd'),
            time: time,
            in: strIn,
            out: strOut,
            isSummary,
            is24,
            signature:
              signature && signature.length > 0
                ? signature
                : [item[0]?.createName]
          })
        }
      }

      // 出入量导出总结/小结签名
      tableData.forEach((item, index) => {
        if (item.isSummary) {
          item.signature = []
          if (tableData[index - 1]) {
            item.signature = tableData[index - 1].signature
          }
        }
      })

      // 药物分组 计算总量
      tableData.forEach(item => {
        if (item.in.length) {
          item.in.forEach((citem, cindex) => {
            if (citem[citem.length - 1] == 'groupId') {
              item.in[cindex] = item.in[cindex].splice(
                item.in[cindex].length - 1
              )
              let str = ''
              let sum = 0
              citem.forEach(citem_ => {
                const [name, dose] = citem_.split('：')
                str += name + ' + '
                sum += Number(dose)
              })
              str = str.slice(0, -3) + ' : ' + sum
              item.in[cindex] = [str]
            }
          })
        }
      })

      for (const i in tableData) {
        tableData[i].sortFlag = Number(
          new Date(tableData[i].date + ' ' + tableData[i].time)
        )
      }
      state.tableData = arrSort(tableData, 'sortFlag')
      const outDetail = [] // 24H总结明细
      const outDetailWorkPlan = [] // 各个班次总结明细
      let out_dbSum = 0

      for (const i in state.tableData) {
        const item = state.tableData[i]
        if (Number(i) !== 0 && state.tableData[i].signature === null) {
          state.tableData[i].signature =
            state.tableData[Number(i) - 1].signature
        }
        const outItem = outMap[item.key]

        if (item.isSummary) {
          if (outDetail.length > 0) {
            //插入大便次数
            const ind = outDetail.findIndex(item => {
              return item.itemCode == 'out_db'
            })
            if (ind > -1) {
              outDetail.splice(ind + 1, 0, {
                medication: '大便次数',
                itemCode: 'out_dbSum',
                ioValue: out_dbSum
              })
            }

            item.out += `（${outDetail
              .map(v => `${v.medication}：${v.ioValue}`)
              .join('；')}）`
            outDetail.length = 0
            out_dbSum = 0
          }
        } else {
          // 统计各个code的量
          outItem.forEach(v => {
            const outDetailItem = outDetail.find(
              v2 => v2.itemCode === v.itemCode
            )
            if (outDetailItem) {
              outDetailItem.ioValue =
                Number(outDetailItem.ioValue) + Number(v.ioValue)
            } else {
              outDetail.push(cloneDeep(v))
            }

            const outDetailWorkPlanItem = outDetailWorkPlan.find(
              v2 => v2.itemCode === v.itemCode
            )
            if (outDetailWorkPlanItem) {
              outDetailWorkPlanItem.ioValue =
                Number(outDetailWorkPlanItem.ioValue) + Number(v.ioValue)
            } else {
              outDetailWorkPlan.push(cloneDeep(v))
            }
          })

          // 大便次数单独计算
          outItem.forEach(item => {
            if (item.itemCode == 'out_db') {
              out_dbSum += 1
            }
          })
        }
      }

      const tableData_ = tableData.filter(item => {
        return item.isSummary && item.in && item.out
      })

      tableData_.forEach(item => {
        item.in = item.in.flat().join('；')
        item.date = item.key
      })

      state.dataList = setData.concat(tableData_)
      state.dataList.sort((a, b) => {
        return Number(new Date(a.date)) - Number(new Date(b.date))
      })
    }

    watch(
      () => props.dataList,
      val => {
        // console.log(val, 'dataList')
        if (val) {
          // setSumData(val)
          state.dataList = val
          state.dateArr = []
          state.recordData = val.map((item, index) => {
            const dateItem = item.rData.find(
              item2 => item2.dictValue == 'date_value'
            )
            state.dateArr[index] = dateItem
            return {
              id: '',
              createTime: dateItem ? dateItem.val : '',
              showValue: '',
              createdBy: ''
            }
          })
        }
      },
      { deep: true, immediate: true }
    )

    watch(
      () => props.titleColumns,
      val => {
        if (val) {
          state.titleColumnsFlat = []
          setTitleColumnsFlat(val)
        }
      },
      {
        immediate: true,
        deep: true
      }
    )

    return {
      ...toRefs(state),
      signPhoto,
      handleRowClick,
      handleCellClick,
      getDocSaveParams
    }
  }
})
</script>

<style lang="scss" scoped>
.icrPartialPage {
  position: relative;
  // width: 1700px;
  overflow: visible;
  display: inline-block;
  // background-color: #ccc;
  box-sizing: border-box;
  //   text-align: center;
  border: none;
}

.is-border {
  border: 1px solid #f0f0f0;
}

.doc-header {
  padding-left: 30px;
  padding-right: 30px;
}

.showing-table {
  box-sizing: border-box;
  // display: inline-block;
  margin: 15px 30px 0;

  // min-width: 100%;
  background-color: #fff;
  font-size: 12px;
  border: 1px solid;
  border-left: none;
}

.showing-thead {
  box-sizing: border-box;
  display: block;
  margin: 0;
  padding: 0;
  width: fit-content;
  // border-top: 1px solid #000;
  // border-left: 1px solid #000;

  // white-space: normal;
  white-space: nowrap;
}

.showing-tr {
  box-sizing: border-box;
  display: block;
  margin: 0;
  padding: 0;
  width: 100%;
  border-top: 1px solid #000;
  // border-left: 1px solid #000;

  // white-space: normal;
  white-space: nowrap;
  vertical-align: top;
}

.showing-cell {
  box-sizing: border-box;
  display: inline-block;
  margin: 0;
  padding: 5px 0;
  height: 100%;
  border-left: 1px solid #000;
  // border-bottom: 1px solid #000;
  vertical-align: middle;
  white-space: normal;
  word-break: break-all;
  overflow-wrap: anywhere;
  text-align: center;
}

.control-text {
  box-sizing: border-box;
  display: inline-block;

  // line-height: 1;
  line-height: 1.25;
  word-break: break-all;
  overflow-wrap: anywhere;
  text-align: left;
  vertical-align: top;
}

.sumCell {
  width: 116px;
  text-align: center;
  border-right: 1px solid #000;
}

.sumCellText {
  border: none;

  span {
    margin-left: 20px;
  }
}

.color-bg {
  background: #f1faf1;
}

.pageNum {
  position: absolute;
  width: 100%;
  bottom: 0;
  left: 0;
  text-align: center;
  padding-bottom: 5px;
}
</style>
